import { ref, reactive, computed, watch, nextTick } from "vue-demi"
import type { PropsType, EmitFlag } from "../type"

function useState(props: PropsType, emit: EmitFlag) {
  const inputRef = ref<HTMLElement>()
  const formData = reactive({
    fileId: 0,
    name: "",
    editable: true,
  })
  const modalFlag = ref(false) // 弹窗是否展开
  // 监听弹窗flag变化
  watch(
    () => props.flag,
    () => {
      modalFlag.value = props.flag
    }
  )
  watch(
    () => modalFlag.value,
    () => {
      emit("update:flag", modalFlag.value)
      if (modalFlag.value) {
        nextTick(() => {
          inputRef.value?.focus()
        })
      } else {
        formData.name = ""
        formData.editable = true
      }
    }
  )

  const modalTitle = computed(() => {
    if (props.handle === "add") {
      return props.isDir ? "新建文件夹" : "新建markdown"
    } else {
      return props.isDir ? "修改文件夹属性" : "修改文件属性"
    }
  })

  return { modalFlag, formData, inputRef, modalTitle }
}
export default useState
